package com.codi.bus.core.service.impl;

import com.codi.base.util.BigDecimalUtil;
import com.codi.base.util.DateUtils;
import com.codi.base.util.MoneyUtils;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.dao.*;
import com.codi.bus.core.domain.*;
import com.codi.bus.core.fund.domain.FundPortfolioTransfer;
import com.codi.bus.core.resultModel.ApplyListResult;
import com.codi.bus.core.resultModel.BaseResult;
import com.codi.bus.core.resultModel.FundNetValueResult;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.MessageService;
import com.codi.bus.core.service.SMSSimpleService;
import com.codi.bus.core.service.model.ApplyModel;
import com.codi.bus.core.service.model.CombSharesQryModel;
import com.codi.bus.core.service.model.DividendModel;
import com.codi.bus.core.service.organ.OrganProfileService;
import com.codi.bus.core.service.util.CalculateAssetsUtils;
import com.codi.bus.core.service.util.HundsunUtils;
import com.codi.bus.core.service.util.ModelPopulateUtils;
import com.codi.bus.util.GeneratorUtil;
import com.codi.trade.dto.CombSharesQryDto;
import com.codi.trade.dto.TradeApplyQryDto;
import com.codi.trade.response.HsTradeApplyQryResponse;
import com.codi.trade.response.HsTradeConfirmQryResponse;
import com.codi.trade.service.TradeApplyQueryService;
import com.codi.trade.service.portfolio.HsCombSharesQryService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by asus on 2018/4/13.
 */
@Slf4j
@Service("messageServiceImpl")
public class MessageServiceImpl implements MessageService {
    @Resource(name = "userDao")
    private UserDao userDao;
    @Autowired
    private HsCombSharesQryService hsCombSharesQryService;

    @Autowired
    private SMSSimpleService smsSimpleService;

    @Autowired
    private FundDetailService fundDetailService;

    @Autowired
    private UserMsgDao userMsgDao;

    @Autowired
    private FundCombinationDao fundCombinationDao;

    @Autowired
    private LookupDao lookupDao;

    @Autowired
    private TradeApplyQueryService tradeApplyQueryService;

    @Autowired
    private FundWarehouseTransferDao fundWarehouseTransferDao;

    @Autowired
    private OrganBankDao organBankDao;

    @Autowired
    private OrganProfileService organProfileService;

    @Autowired
    private OrganAgentDao organAgentDao;

    @Autowired
    private TradeNoticeDao tradeNoticeDao;

    /**
     * 给企业相关人员发送短信
     *
     * @param profileId 企业id
     * @param message   短信内容
     */
    private void sendOrganSMS(Long profileId, String message) {
        // 如果是机构需要同时发送短信给经办人和报备人
        if (profileId != null) {
            OrganProfile organProfile = organProfileService.getById(profileId);
            Long agentId = organProfile.getOrganAgentId();
            OrganAgent organAgent = organAgentDao.selectByPrimaryKey(agentId);
            // 经办人手机号
            String agentMobile = organAgent.getOrganAgentMobile();
            smsSimpleService.sendMessage(agentMobile, message, GeneratorUtil.getRandomNum(5));
            List<TradeNotice> tradeNotices = tradeNoticeDao.getListByProfileId(profileId.toString());
            if (tradeNotices != null && !tradeNotices.isEmpty()) {
                tradeNotices.forEach(tradeNotice ->
                    smsSimpleService.sendMessage(tradeNotice.getNoticeMobile(), message, GeneratorUtil.getRandomNum(5))
                );
            }
        }
    }

    @Override
    public void sendMessageAllUser(String message) {
        List<User> users = userDao.getAllUser();
        users.forEach(user ->
            smsSimpleService.sendMessage(user.getUserMobile(), message, GeneratorUtil.getRandomNum(5))
        );
        //smsSimpleService.sendMessage(mobile, message, GeneratorUtil.getRandomNum(5));
    }


    @Override
    public int getUserSysMessageCounts(Long userId) {
        User user = userDao.getEntity(userId);
        return user.getUserSysMessageCounts();
    }

    /**
     * 插入消息到记录表
     *
     * @param tradeOrder
     * @param orderFund
     * @param tradeRecord
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFundUserMsg(TradeOrder tradeOrder, OrderFund orderFund, HsTradeConfirmQryResponse tradeRecord) throws Exception {
        String smessage;
        UserMsg userMsg = new UserMsg();
        UserMsg targetUserMsg = null;
        userMsg.setUserId(tradeOrder.getUserId());
        FundNetValueResult netValue = fundDetailService.getFundNetValue(tradeRecord.getFund_code(), DateUtils.addDay(new Date(), -1));
        FundNetValueResult targetNetValue = new FundNetValueResult();
        if (!Strings.isNullOrEmpty(tradeRecord.getTarget_fund_code())) {
            targetNetValue = fundDetailService.getFundNetValue(tradeRecord.getTarget_fund_code(), DateUtils.addDay(new Date(), -1));
        }
        //获取T0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_T0FUND);
        if (tradeOrder.getProfileId() != null) {
            lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
        }
        //消息类型
        if (CalculateAssetsUtils.isT0Fund(lookups, orderFund.getFundCode())) {
            userMsg.setMsgType(1);
        } else {
            userMsg.setMsgType(2);
        }
        userMsg.setAllotNo(orderFund.getExternalApplyNo());
        String content;
        User user = userDao.getEntity(tradeOrder.getUserId());
        String ranNumber = GeneratorUtil.getRandomNum(6);
        switch (tradeOrder.getTradeType()) {
            //申购
            case GlobalConstant.TRADE_TYPE_BUY:
            case GlobalConstant.TRADE_TYPE_OFFLINE_BUY:
                userMsg.setTitleType(1);
                userMsg.setMsgTitle(GlobalConstant.BUY_CONFIRM_SUCCESS);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n申购金额：" + tradeRecord.getBalance() + "元";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsg.setProfileId(tradeOrder.getProfileId());
                userMsgDao.insert(userMsg);
                log.info("申购成功消息添加成功");
                // 申购成功短信内容
                smessage = getSendMessage(tradeOrder.getApplyDate(), 0, true, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getBalance(), tradeRecord.getTrade_confirm_type(), netValue.getUnitNV());
                String m = smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("return:{}", m);
                log.info("申购成功：发送短信内容：{}", smessage);
                break;
            //赎回
            case GlobalConstant.TRADE_TYPE_SELL:
                userMsg.setTitleType(2);
                userMsg.setMsgTitle(GlobalConstant.SELL_CONFIRM_SUCCESS);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n赎回份额：" + tradeRecord.getShares() + "份";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsg.setProfileId(tradeOrder.getProfileId());

                userMsgDao.insert(userMsg);
                log.info("赎回成功消息添加成功");

                // 赎回成功短信内容
                smessage = getSendMessage(tradeOrder.getApplyDate(), 1, true, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getTrade_confirm_balance(), tradeRecord.getShares(), netValue.getUnitNV());
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);

                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("赎回成功：发送短信内容：{}", smessage);
                break;
            case GlobalConstant.TRADE_TYPE_FAST_REDEEM:
                return;
            case GlobalConstant.TRADE_TYPE_SELL_THEN_BUY:
            case GlobalConstant.TRADE_TYPE_SELL_THEN_BUY_WALLET:
                userMsg.setTitleType(2);
                userMsg.setMsgTitle(GlobalConstant.SELL_CONFIRM_SUCCESS);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n赎回份额：" + tradeRecord.getShares() + "份";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsg.setMsgType(1);
                userMsg.setProfileId(tradeOrder.getProfileId());
                targetUserMsg = new UserMsg();
                targetUserMsg.setTitleType(1);
                targetUserMsg.setMsgTitle(GlobalConstant.BUY_CONFIRM_SUCCESS);
                content = "基金名称：" + targetNetValue.getChiNameAbbr() + "\n申购金额：" + tradeRecord.getTrade_confirm_balance() + "元";
                targetUserMsg.setMsgContent(content);
                targetUserMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                targetUserMsg.setMsgState(0);
                targetUserMsg.setMsgType(2);
                targetUserMsg.setProfileId(tradeOrder.getProfileId());

                userMsgDao.insert(userMsg);
                userMsgDao.insert(targetUserMsg);
                log.info("赎回转购成功消息添加成功");

                // 转购 先发送赎回，在发送申购
                smessage = getSendMessage(tradeOrder.getApplyDate(), 1, true, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getTrade_confirm_balance(), tradeRecord.getShares(), netValue.getUnitNV());
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);

                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("赎回成功：发送短信内容：{}", smessage);
                // 晚10秒发送申购短信
                Thread.sleep(10000);
                smessage = getSendMessage(tradeOrder.getApplyDate(), 0, true, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getBalance(), tradeRecord.getTrade_confirm_type(), netValue.getUnitNV());
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                log.info("申购成功：发送短信内容：{}", smessage);
                break;
            default:
                break;
        }
    }

    /**
     * 插入失败消息到记录表
     *
     * @param tradeOrder
     * @param orderFund
     * @param tradeRecord
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFundFailUserMsg(TradeOrder tradeOrder, OrderFund orderFund, HsTradeConfirmQryResponse tradeRecord) throws Exception {
        String smessage;
        UserMsg userMsg = new UserMsg();
        UserMsg targetUserMsg = null;
        userMsg.setUserId(tradeOrder.getUserId());
        FundNetValueResult netValue = fundDetailService.getFundNetValue(tradeRecord.getFund_code(), DateUtils.addDay(new Date(), -1));
        FundNetValueResult targetNetValue = new FundNetValueResult();
        if (!Strings.isNullOrEmpty(tradeRecord.getTarget_fund_code())) {
            targetNetValue = fundDetailService.getFundNetValue(tradeRecord.getTarget_fund_code(), DateUtils.addDay(new Date(), -1));
        }
        //获取T0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_T0FUND);
        if (tradeOrder.getProfileId() != null) {
            lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
        }
        //消息类型
        if (CalculateAssetsUtils.isT0Fund(lookups, orderFund.getFundCode())) {
            userMsg.setMsgType(1);
        } else {
            userMsg.setMsgType(2);
        }
        userMsg.setAllotNo(orderFund.getExternalApplyNo());
        String content;
        User user = userDao.getEntity(tradeOrder.getUserId());
        String ranNumber = GeneratorUtil.getRandomNum(6);
        switch (tradeOrder.getTradeType()) {
            //申购
            case GlobalConstant.TRADE_TYPE_BUY:
                userMsg.setTitleType(1);
                userMsg.setMsgTitle(GlobalConstant.BUY_CONFIRM_FAIL);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n申购金额：" + tradeRecord.getBalance() + "元";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsg.setProfileId(tradeOrder.getProfileId());
                userMsgDao.insert(userMsg);
                log.info("申购失败消息添加成功");

                // 申购成功短信内容
                smessage = getSendMessage(tradeOrder.getApplyDate(), 0, false, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getBalance(), tradeRecord.getTrade_confirm_type(), netValue.getUnitNV());
                String m = smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);

                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("return:{}", m);
                log.info("申购失败：发送短信内容：{}", smessage);
                break;
            //赎回
            case GlobalConstant.TRADE_TYPE_SELL:
                userMsg.setTitleType(2);
                userMsg.setMsgTitle(GlobalConstant.SELL_CONFIRM_FAIL);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n赎回份额：" + tradeRecord.getShares() + "份";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsg.setProfileId(tradeOrder.getProfileId());
                userMsgDao.insert(userMsg);
                log.info("赎回失败消息添加成功");

                // 赎回成功短信内容
                smessage = getSendMessage(tradeOrder.getApplyDate(), 1, false, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getTrade_confirm_balance(), tradeRecord.getShares(), netValue.getUnitNV());
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);

                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("赎回失败：发送短信内容：{}", smessage);
                break;
            case GlobalConstant.TRADE_TYPE_FAST_REDEEM:
                return;
            case GlobalConstant.TRADE_TYPE_SELL_THEN_BUY:
            case GlobalConstant.TRADE_TYPE_SELL_THEN_BUY_WALLET:
                userMsg.setTitleType(2);
                userMsg.setMsgTitle(GlobalConstant.SELL_CONFIRM_FAIL);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n赎回份额：" + tradeRecord.getTrade_confirm_type() + "份";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsg.setMsgType(1);
                userMsg.setProfileId(tradeOrder.getProfileId());
                targetUserMsg = new UserMsg();
                targetUserMsg.setTitleType(1);
                targetUserMsg.setMsgTitle(GlobalConstant.BUY_CONFIRM_FAIL);
                content = "基金名称：" + targetNetValue.getChiNameAbbr() + "\n申购金额：" + tradeRecord.getTrade_confirm_balance() + "元";
                targetUserMsg.setMsgContent(content);
                targetUserMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                targetUserMsg.setMsgState(0);
                targetUserMsg.setMsgType(2);
                targetUserMsg.setProfileId(tradeOrder.getProfileId());
                userMsgDao.insert(userMsg);
                userMsgDao.insert(targetUserMsg);
                log.info("赎回转购失败消息添加成功");

                // 转购 先发送赎回，在发送申购
                smessage = getSendMessage(tradeOrder.getApplyDate(), 1, false, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getTrade_confirm_balance(), tradeRecord.getShares(), netValue.getUnitNV());
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);

                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("赎回失败：发送短信内容：{}", smessage);
                // 晚10秒发送申购短信
                Thread.sleep(10000);
                smessage = getSendMessage(tradeOrder.getApplyDate(), 0, false, netValue.getChiNameAbbr(), tradeRecord.getFund_code(), tradeRecord.getBalance(), tradeRecord.getTrade_confirm_type(), netValue.getUnitNV());
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                // 给机构相关人员发送短信
                sendOrganSMS(userMsg.getProfileId(), smessage);
                log.info("申购失败：发送短信内容：{}", smessage);
                break;
            default:
                break;
        }
    }

    /**
     * 插入组合消息到记录表
     *
     * @param tradeOrder
     * @param orderFund
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePortfolioFundUserMsg(TradeOrder tradeOrder, PortfolioFundOrder orderFund, List<HsTradeConfirmQryResponse> hsTradeConfirmQryResponseList) throws Exception {
        String smessage;
        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(tradeOrder.getUserId());
        userMsg.setMsgType(3);
        userMsg.setAllotNo(orderFund.getExternalApplyNo());
        //获取组合名称
        String portfolioName = "";
        List<FundCombination> fundCombinations = fundCombinationDao.queryFundCombinations();
        for (FundCombination fundCombination : fundCombinations) {
            if (fundCombination.getCombinationCode().equals(orderFund.getPortfolioCode())) {
                portfolioName = fundCombination.getCombinationName();
            }
        }
        //累加组合 金额和份额
        BigDecimal balance = new BigDecimal(0);
        BigDecimal share = new BigDecimal(0);
        BigDecimal confirm_balance = new BigDecimal(0);
        BigDecimal confirm_type = new BigDecimal(0);
        for (HsTradeConfirmQryResponse response : hsTradeConfirmQryResponseList) {
            // 申购
            balance = MoneyUtils.add(balance, BigDecimalUtil.ConvertToBigDecimal(response.getBalance()));
            confirm_type = MoneyUtils.add(confirm_type, BigDecimalUtil.ConvertToBigDecimal(response.getTrade_confirm_type()));
            // 赎回
            confirm_balance = MoneyUtils.add(confirm_balance, BigDecimalUtil.ConvertToBigDecimal(response.getTrade_confirm_balance()));
            share = MoneyUtils.add(share, BigDecimalUtil.ConvertToBigDecimal(response.getShares()));
        }

        String content;
        User user = userDao.getEntity(tradeOrder.getUserId());
        String ranNumber = GeneratorUtil.getRandomNum(6);
        switch (tradeOrder.getTradeType()) {
            //申购
            case GlobalConstant.TRADE_TYPE_BUY:
            case GlobalConstant.TRADE_TYPE_OFFLINE_BUY:
                userMsg.setTitleType(1);
                userMsg.setMsgTitle(GlobalConstant.BUY_CONFIRM_SUCCESS);
                content = "组合名称：" + portfolioName + "\n申购金额：" + balance + "元";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsgDao.insert(userMsg);
                log.info("组合申购成功消息添加成功");

                // 申购成功短信内容
                smessage = getSendMessage(tradeOrder.getApplyDate(), 2, true, portfolioName, orderFund.getPortfolioCode(), balance + "", confirm_type + "", null);
                String m = smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                log.info("return:{}", m);
                log.info("组合申购成功：发送短信内容：{}", smessage);
                break;
            //赎回
            case GlobalConstant.TRADE_TYPE_SELL:
                userMsg.setTitleType(2);
                userMsg.setMsgTitle(GlobalConstant.SELL_CONFIRM_SUCCESS);
                content = "组合名称：" + portfolioName + "\n赎回份额：" + share + "份";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsgDao.insert(userMsg);
                log.info("组合赎回成功消息添加成功");

                smessage = getSendMessage(tradeOrder.getApplyDate(), 3, true, portfolioName, orderFund.getPortfolioCode(), confirm_balance + "", share + "", null);
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                log.info("组合赎回成功：发送短信内容：{}", smessage);
                break;
            default:
                break;
        }
    }

    /**
     * 插入组合失败消息到记录表
     *
     * @param tradeOrder
     * @param orderFund
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePortfolioFundFailUserMsg(TradeOrder tradeOrder, PortfolioFundOrder orderFund, List<HsTradeConfirmQryResponse> hsTradeConfirmQryResponseList) throws Exception {
        String smessage;
        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(tradeOrder.getUserId());
        userMsg.setMsgType(3);
        userMsg.setAllotNo(orderFund.getExternalApplyNo());
        //获取组合名称
        String portfolioName = "";
        List<FundCombination> fundCombinations = fundCombinationDao.queryFundCombinations();
        for (FundCombination fundCombination : fundCombinations) {
            if (fundCombination.getCombinationCode().equals(orderFund.getPortfolioCode())) {
                portfolioName = fundCombination.getCombinationName();
            }
        }
        //累加组合 金额和份额
        BigDecimal balance = new BigDecimal(0);
        BigDecimal share = new BigDecimal(0);
        BigDecimal confirm_balance = new BigDecimal(0);
        BigDecimal confirm_type = new BigDecimal(0);
        for (HsTradeConfirmQryResponse response : hsTradeConfirmQryResponseList) {
            // 申购
            balance = MoneyUtils.add(balance, BigDecimalUtil.ConvertToBigDecimal(response.getBalance()));
            confirm_type = MoneyUtils.add(confirm_type, BigDecimalUtil.ConvertToBigDecimal(response.getTrade_confirm_type()));
            // 赎回
            confirm_balance = MoneyUtils.add(confirm_balance, BigDecimalUtil.ConvertToBigDecimal(response.getTrade_confirm_balance()));
            share = MoneyUtils.add(share, BigDecimalUtil.ConvertToBigDecimal(response.getShares()));
        }

        String content;
        User user = userDao.getEntity(tradeOrder.getUserId());
        String ranNumber = GeneratorUtil.getRandomNum(6);
        switch (tradeOrder.getTradeType()) {
            //申购
            case GlobalConstant.TRADE_TYPE_BUY:
            case GlobalConstant.TRADE_TYPE_OFFLINE_BUY:
                userMsg.setTitleType(1);
                userMsg.setMsgTitle(GlobalConstant.BUY_CONFIRM_FAIL);
                content = "组合名称：" + portfolioName + "\n申购金额：" + balance + "元";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsgDao.insert(userMsg);
                log.info("组合申购失败消息添加成功");

                // 申购短信内容
                smessage = getSendMessage(tradeOrder.getApplyDate(), 2, false, portfolioName, orderFund.getPortfolioCode(), balance + "", confirm_type + "", null);
                String m = smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                log.info("return:{}", m);
                log.info("组合申购失败：发送短信内容：{}", smessage);
                break;
            //赎回
            case GlobalConstant.TRADE_TYPE_SELL:
                userMsg.setTitleType(2);
                userMsg.setMsgTitle(GlobalConstant.SELL_CONFIRM_FAIL);
                content = "组合名称：" + portfolioName + "\n赎回份额：" + share + "份";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsgDao.insert(userMsg);
                log.info("组合赎回失败消息添加成功");

                smessage = getSendMessage(tradeOrder.getApplyDate(), 3, false, portfolioName, orderFund.getPortfolioCode(), confirm_balance + "", share + "", null);
                smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
                log.info("组合赎回失败：发送短信内容：{}", smessage);
                break;
            default:
                break;
        }
    }

    /**
     * 插入组合调仓成功消息到记录表
     *
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePortfolioTransferUserMsg(FundPortfolioTransfer portfolioTransfer) throws Exception {
        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(portfolioTransfer.getUserId());
        userMsg.setMsgType(3);
        //获取组合名称
        String portfolioName = "";
        List<FundCombination> fundCombinations = fundCombinationDao.queryFundCombinations();
        for (FundCombination fundCombination : fundCombinations) {
            if (fundCombination.getCombinationCode().equals(portfolioTransfer.getPortfolioCode())) {
                portfolioName = fundCombination.getCombinationName();
            }
        }
        userMsg.setAllotNo(portfolioTransfer.getAllotNo());
        userMsg.setTitleType(5);
        userMsg.setMsgTitle(GlobalConstant.PORTFOLIO_TRANSFER_SUCCESS);
        String content = "组合名称：" + portfolioName;
        userMsg.setMsgContent(content);
        userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
        userMsg.setMsgState(0);
        userMsgDao.insert(userMsg);
        log.info("组合调仓成功消息添加成功");

        User user = userDao.getEntity(portfolioTransfer.getUserId());
        String ranNumber = GeneratorUtil.getRandomNum(6);
        String smessage = getSendMessage(portfolioTransfer.getCreateDate(), 4, true, portfolioName, null, null, null, null);
        log.info("调仓成功：发送短信内容：{}", smessage);
        smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
    }

    /**
     * 插入组合调仓失败消息到记录表
     *
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePortfolioTransferFailUserMsg(FundPortfolioTransfer portfolioTransfer) throws Exception {
        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(portfolioTransfer.getUserId());
        userMsg.setMsgType(3);
        userMsg.setAllotNo(portfolioTransfer.getAllotNo());
        //获取组合名称
        String portfolioName = "";
        List<FundCombination> fundCombinations = fundCombinationDao.queryFundCombinations();
        for (FundCombination fundCombination : fundCombinations) {
            if (fundCombination.getCombinationCode().equals(portfolioTransfer.getPortfolioCode())) {
                portfolioName = fundCombination.getCombinationName();
            }
        }

        userMsg.setTitleType(5);
        userMsg.setMsgTitle(GlobalConstant.PORTFOLIO_TRANSFER_FAIL);
        String content = "组合名称：" + portfolioName;
        userMsg.setMsgContent(content);
        userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
        userMsg.setMsgState(0);
        userMsgDao.insert(userMsg);
        log.info("组合调仓失败消息添加成功");

        User user = userDao.getEntity(portfolioTransfer.getUserId());
        String ranNumber = GeneratorUtil.getRandomNum(6);
        String smessage = getSendMessage(portfolioTransfer.getCreateDate(), 4, false, portfolioName, null, null, null, null);
        smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
        log.info("调仓失败：发送短信内容：{}", smessage);
    }


    /**
     * 定投的消息
     *
     * @param tradeOrder
     * @param orderFund
     * @param tradeApplyRecord
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFundFixUserMsg(TradeOrder tradeOrder, OrderFund orderFund, HsTradeApplyQryResponse tradeApplyRecord) throws Exception {
        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(tradeOrder.getUserId());
        FundNetValueResult netValue = fundDetailService.getFundNetValue(tradeApplyRecord.getFund_code(), DateUtils.addDay(new Date(), -1));
        //获取T0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_T0FUND);
        //消息类型
        if (CalculateAssetsUtils.isT0Fund(lookups, orderFund.getFundCode())) {
            userMsg.setMsgType(1);
        } else {
            userMsg.setMsgType(2);
        }
        userMsg.setAllotNo(orderFund.getExternalApplyNo());
        String content;
        switch (tradeOrder.getTradeType()) {
            //定投
            case GlobalConstant.TRADE_TYPE_FIX:
                userMsg.setTitleType(3);
                userMsg.setMsgTitle(GlobalConstant.FIX_CONFIRM_SUCCESS);
                content = "基金名称：" + netValue.getChiNameAbbr() + "\n定投金额：" + tradeApplyRecord.getBalance() + "元";
                userMsg.setMsgContent(content);
                userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
                userMsg.setMsgState(0);
                userMsgDao.insert(userMsg);
                log.info("定投消息添加成功");

                break;
            default:
                break;
        }
    }

    /**
     * 插入快赎消息到记录表
     *
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatefastRedeemUserMsg(BigDecimal shares, String fundName, Long userId, String externalApplyNo, Long profileId) throws Exception {
        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(userId);
        userMsg.setMsgType(1);
        userMsg.setAllotNo(externalApplyNo);
        userMsg.setTitleType(2);
        userMsg.setMsgTitle(GlobalConstant.FAST_REDEEM_SUCCESS);
        String content = "基金名称：" + fundName + "\n快速取现：" + shares + "元";
        userMsg.setMsgContent(content);
        userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
        userMsg.setMsgState(0);
        userMsg.setProfileId(profileId);
        userMsgDao.insert(userMsg);
        log.info("快赎消息添加成功");
    }

    /**
     * 插入组合撤单消息到记录表
     *
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePortfolioUndoUserMsg(Long userId, String portfolioApplyNo, String portfolioCode) throws Exception {
        TradeApplyQryDto tradeApplyQryDto = TradeApplyQryDto.builder()
            .request_num("50")
            .reqry_recordsum_flag("1")
            .qry_beginrownum("1")
            .sort_direction("1")
            .portfolio_allot_no(portfolioApplyNo)
            .build();
        Map<String, Object> map = tradeApplyQueryService.query(tradeApplyQryDto);
        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        ApplyListResult result = new ApplyListResult();
        HundsunUtils.ConvertToList(map, list, result);
        if (!result.getSuccess()) {
            log.warn("queryApply - applyNo={}, no apply trade order found", portfolioApplyNo);
            return;
        }

        // 交易业务名称
        List<Lookup> tradeLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_BUSINAME);
        // 银行名称
        List<Lookup> bankLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);

        // populate
        List<ApplyModel> applys = ModelPopulateUtils.populateApply(list, result, tradeLookups, bankLookups);
        if (applys == null || applys.size() == 0) {
            return;
        }
        BigDecimal balance = new BigDecimal(0);
        BigDecimal share = new BigDecimal(0);
        //获取组合名称
        String portfolioName = "";
        List<FundCombination> fundCombinations = fundCombinationDao.queryFundCombinations();
        for (FundCombination fundCombination : fundCombinations) {
            if (fundCombination.getCombinationCode().equals(portfolioCode)) {
                portfolioName = fundCombination.getCombinationName();
            }
        }
        for (ApplyModel applyModel : applys) {
            if (GlobalConstant.TACONFIRM_FLAG_UNDO.equals(applyModel.getTAConfirmFlag())) {
                balance = MoneyUtils.add(balance, applyModel.getBalance());
                share = MoneyUtils.add(share, applyModel.getShares());
            }
        }
        if (!applys.isEmpty()) {
            UserMsg userMsg = new UserMsg();
            userMsg.setUserId(userId);
            userMsg.setMsgType(3);
            String content = "";
            switch (applys.get(0).getFundBusinCode()) {
                case GlobalConstant.FUND_BUSIN_CODE_APPLY_BUY:
                    userMsg.setTitleType(1);

                    content = "组合名称：" + portfolioName + "\n申购金额：" + balance + "元";
                    break;
                case GlobalConstant.FUND_BUSIN_CODE_APPLY_SELL:
                    userMsg.setTitleType(2);
                    content = "组合名称：" + portfolioName + "\n赎回份额：" + share + "份";
                    break;
                default:
                    break;
            }
            userMsg.setMsgTitle(GlobalConstant.UNDO_SUCCESS);
            userMsg.setAllotNo(portfolioApplyNo);
            userMsg.setMsgContent(content);
            userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
            userMsg.setMsgState(0);
            userMsgDao.insert(userMsg);
            log.info("组合撤单消息添加成功");
        }
    }

    /**
     * 插入基金撤单消息到记录表
     *
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUndoUserMsg(Long userId, String applyNo, Long profileId) throws Exception {
        TradeApplyQryDto tradeApplyQryDto = TradeApplyQryDto.builder()
            .request_num("50")
            .reqry_recordsum_flag("1")
            .qry_beginrownum("1")
            .sort_direction("1")
            .allot_no(applyNo)
            .build();
        Map<String, Object> map = tradeApplyQueryService.query(tradeApplyQryDto);
        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        ApplyListResult result = new ApplyListResult();
        HundsunUtils.ConvertToList(map, list, result);
        if (!result.getSuccess()) {
            log.warn("queryApply - applyNo={}, no apply trade order found", applyNo);
            return;
        }

        // 交易业务名称
        List<Lookup> tradeLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_BUSINAME);
        // 银行名称
        List<Lookup> bankLookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);
        //获取T0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_T0FUND);

        // populate
        List<ApplyModel> applys = ModelPopulateUtils.populateApply(list, result, tradeLookups, bankLookups);
        if (applys == null || applys.size() == 0) {
            return;
        }
        ApplyModel applyModel = applys.get(0);
        FundNetValueResult netValue = fundDetailService.getFundNetValue(applyModel.getFundCode(), DateUtils.addDay(new Date(), -1));
        if (applyModel != null) {
            UserMsg userMsg = new UserMsg();
            userMsg.setUserId(userId);
            if (CalculateAssetsUtils.isT0Fund(lookups, applyModel.getFundCode())) {
                userMsg.setMsgType(1);
            } else {
                userMsg.setMsgType(2);
            }
            String content = "";
            switch (applyModel.getFundBusinCode()) {
                case GlobalConstant.FUND_BUSIN_CODE_APPLY_BUY:
                    userMsg.setTitleType(1);
                    content = "基金名称：" + netValue.getChiNameAbbr() + "\n申购金额：" + applyModel.getBalance() + "元";
                    break;
                case GlobalConstant.FUND_BUSIN_CODE_APPLY_SELL:
                    userMsg.setTitleType(2);
                    content = "基金名称：" + netValue.getChiNameAbbr() + "\n赎回份额：" + applyModel.getShares() + "份";
                    break;
                default:
                    break;
            }
            userMsg.setMsgTitle(GlobalConstant.UNDO_SUCCESS);
            userMsg.setMsgContent(content);
            userMsg.setAllotNo(applyNo);
            userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
            userMsg.setMsgState(0);
            userMsg.setProfileId(profileId);
            userMsgDao.insert(userMsg);
            log.info("基金撤单消息添加成功");

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDividendUserMsg(DividendModel dividendModel, User user) throws Exception {
        //通过 日期 基金  交易账号  分红方式跑  匹配
        List<OrganBank> organBanks = organBankDao.selectByTradeAccount(dividendModel.getTradeAccount());
        // 获取T+0基金
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_T0FUND);
        Long profileId = null;
        if (!organBanks.isEmpty()) {
            // 获取T+0基金
            lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
            profileId = organBanks.get(0).getProfileId();
        }
        String dividendRecord = dividendModel.getDividendDate() + dividendModel.getFundCode() + dividendModel.getTradeAccount() + dividendModel.getAutoBuy();
        if (profileId != null) {
            dividendRecord = dividendModel.getDividendDate() + dividendModel.getFundCode() + dividendModel.getTradeAccount() + dividendModel.getAutoBuy() + profileId;
        }
        int count = userMsgDao.selectByDividend(user.getUserId(), dividendRecord);
        if (count > 0) {
            return;
        }
        FundNetValueResult netValue = fundDetailService.getFundNetValue(dividendModel.getFundCode(), DateUtils.addDay(new Date(), -1));

        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(user.getUserId());
        if (dividendModel.getTradeAccount().startsWith("ZH")) {
            userMsg.setMsgType(3);
        } else {
            if (CalculateAssetsUtils.isT0Fund(lookups, dividendModel.getFundCode())) {
                userMsg.setMsgType(1);
            } else {
                userMsg.setMsgType(2);
            }
        }
        userMsg.setAllotNo(dividendModel.getTaSerialId());
        userMsg.setTitleType(4);
        userMsg.setMsgTitle(GlobalConstant.DIVIDEND_CONFIRM_SUCCESS);
        String content = "";
        if (GlobalConstant.AUTO_BUY.equals(dividendModel.getAutoBuy())) {
            content = "基金名称：" + netValue.getChiNameAbbr() + "\n红利再投：" + dividendModel.getDividendShare() + "份";
        } else if (GlobalConstant.CASH_DIVIDEND.equals(dividendModel.getAutoBuy())) {
            content = "基金名称：" + netValue.getChiNameAbbr() + "\n现金分红：" + dividendModel.getTotalDividendBalance() + "元";
        }

        userMsg.setMsgContent(content);
        userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
        userMsg.setMsgState(0);
        userMsg.setDividendRecord(dividendRecord);
        userMsg.setProfileId(profileId);
        userMsgDao.insert(userMsg);
        log.info("分红消息添加成功");

        if (GlobalConstant.CASH_DIVIDEND.equals(dividendModel.getAutoBuy())) {
            String ranNumber = GeneratorUtil.getRandomNum(6);
            String smessage = getSendMessage(new Date(), 5, false, netValue.getChiNameAbbr(), dividendModel.getFundCode(), dividendModel.getTotalDividendBalance() + "", null, null);
            smsSimpleService.sendMessage(user.getUserMobile(), smessage, ranNumber);
            log.info("发送分红成功：发送短信内容：{}", smessage);
        }
    }

    /**
     * 定投申购确认
     *
     * @param applyModel
     * @param user
     * @param lookups
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFixUserMsg(ApplyModel applyModel, User user, List<Lookup> lookups) throws Exception {
        //通过 日期 基金  交易账号  分红方式跑  匹配
        int count = userMsgDao.selectByAllotNo(user.getUserId(), applyModel.getAllotNo());
        if (count > 0) {
            return;
        }
        FundNetValueResult netValue = fundDetailService.getFundNetValue(applyModel.getFundCode(), DateUtils.addDay(new Date(), -1));

        UserMsg userMsg = new UserMsg();
        userMsg.setUserId(user.getUserId());
        if (applyModel.getTradeAcco().startsWith("ZH")) {
            userMsg.setMsgType(3);
        } else {
            if (CalculateAssetsUtils.isT0Fund(lookups, applyModel.getFundCode())) {
                userMsg.setMsgType(1);
            } else {
                userMsg.setMsgType(2);
            }
        }
        userMsg.setAllotNo(applyModel.getAllotNo());
        userMsg.setTitleType(3);
        userMsg.setMsgTitle(GlobalConstant.FIX_CONFIRM_SUCCESS);
        String content = "基金名称：" + netValue.getChiNameAbbr() + "\n申购金额：" + applyModel.getBalance() + "元";

        userMsg.setMsgContent(content);
        userMsg.setMsgDateTime(DateUtils.getNormalFormatDateTime());
        userMsg.setMsgState(0);
        userMsgDao.insert(userMsg);
        log.info("定投消息插入成功");
        log.info("定投申购成功");
    }

    /**
     * 拼接短信内容
     *
     * @param date     确认时间
     * @param i        区分业务  0 申购，1 赎回，2 组合申购，3 组合赎回，4 组合调仓， 5 分红
     * @param flag     成功 true 失败 false
     * @param fundName 基金名称
     * @param fundCode 基金代码
     * @param balance  交易金额
     * @param shares   确认份额
     * @param unitNVs  净值
     * @return 短信内容
     */
    private String getSendMessage(Date date, int i, boolean flag, String fundName, String fundCode, String balance, String shares, BigDecimal unitNVs) {
        String message;
        int month = DateUtils.getMonth(date);
        int day = DateUtils.getDay(date);
        int hour = DateUtils.getHour(date);
        int minute = DateUtils.getMinute(date);
        message = "【科地基金】尊敬的客户，您于";
        message += String.format("%02d", month) + "月" + String.format("%02d", day) + "日 " + String.format("%02d", hour) + ":" + String.format("%02d", minute);
        String fundCodeReal = "";
        String end = "可登录科地基金APP查看，客服热线：0571-86915761";
        String unitNV = "";
        if (unitNVs != null) {
            unitNV = BigDecimalUtil.ConvertToString(unitNVs, 4);
        }
        switch (i) {
            case 0:
                // 申购
                 /*
                    【科地基金】尊敬的客户，您于04月10日 10:09申购北信瑞丰宜投宝A（000871）已确认成功，
                    申请金额2000.00元，确认份额2000.00份，成交净值为1.0000，可登陆科地基金APP查看，客服热线0571-86915761
                 */
                message += "申购";
                if (StringUtils.isNotBlank(fundCode)) {
                    fundCodeReal = "(" + fundCode + ")";
                }
                // 申请金额
                balance = "申请金额" + balance + "元，";
                // 确认份额
                shares = "确认份额" + shares + "份，";
                // 成交净值
                if (StringUtils.isNotBlank(unitNV)) {
                    unitNV = "成交净值为" + unitNV + "，";
                }
                message += fundName + fundCodeReal;
                if (flag) {
                    message += "已确认成功，" + balance + shares + unitNV;
                } else {
                    message += "确认失败，" + balance + "预计2个工作日内退款回您的银行账户，";
                }
                message += end;
                return message;

            case 1:
                // 赎回
                /*
                    科地基金】尊敬的客户，您于04月10日 10:09赎回北信瑞丰宜投宝A（000871）已确认成功，
                    赎回份额2000.00份，赎回金额5832.00元，成交净值为1.5290，
                    赎回款预计在3~5个工作日内划入您的银行账户，可登陆科地基金APP查看，客服热线0571-86915761
                 */
                message += "赎回";
                if (StringUtils.isNotBlank(fundCode)) {
                    fundCodeReal = "(" + fundCode + ")";
                }
                // 赎回份额
                shares = "赎回份额" + shares + "份，";
                // 赎回金额
                balance = "赎回金额" + balance + "元，";
                // 成交净值
                if (StringUtils.isNotBlank(unitNV)) {
                    unitNV = "成交净值为" + unitNV + "，";
                }
                message += fundName + fundCodeReal;
                if (flag) {
                    message += "已确认成功，" + shares + balance + unitNV + "赎回款预计在3~5个工作日内划入您的银行账户，";
                } else {
                    message += "确认失败，" + shares;
                }
                message += end;
                return message;
            // 组合 申购
            case 2:
                message += "申购";
                if (StringUtils.isNotBlank(fundCode)) {
                    fundCodeReal = "(" + fundCode + ")";
                }
                // 申请金额
                balance = "申请金额" + balance + "元，";
                // 确认份额
                shares = "确认份额" + shares + "份，";
                message += fundName + fundCodeReal;
                if (flag) {
                    message += "已确认成功，" + balance + shares;
                } else {
                    message += "确认失败，" + balance + "预计2个工作日内退款回您的银行账户，";
                }
                message += end;
                return message;

            case 3:
                // 组合 赎回
                /*
                    科地基金】尊敬的客户，您于04月10日 10:09赎回组合A（0130）已确认成功，
                    赎回份额2000.00份，赎回金额5832.00元，
                    赎回款预计在3~5个工作日内划入您的银行账户，可登陆科地基金APP查看，客服热线0571-86915761
                 */
                message += "赎回";
                if (StringUtils.isNotBlank(fundCode)) {
                    fundCodeReal = "(" + fundCode + ")";
                }
                // 赎回份额
                shares = "赎回份额" + shares + "份，";
                // 赎回金额
                balance = "赎回金额" + balance + "元，";
                message += fundName + fundCodeReal;
                if (flag) {
                    message += "已确认成功，" + shares + balance + "赎回款预计在3~5个工作日内划入您的银行账户，";
                } else {
                    message += "确认失败，" + shares;
                }
                message += end;
                return message;
            // 组合调仓
            case 4:
                /*
                【科地基金】尊敬的客户，您于04月10日 10:09发起的瑞富进取组合调仓完成，可登陆科地基金APP查看，客服热线0571-86915761
                */
                if (flag) {

                    message += "发起的" + fundName + "调仓完成，";
                } else {
                    message += "发起的" + fundName + "调仓失败，";
                }
                message += end;
                return message;
            // 分红
            case 5:
                /*
                    【科地基金】尊敬的客户，您持有的北信瑞丰宜投宝A（000871）于04月10日发放现金分红100.00元，
                    资金将于2个工作日左右划入您的银行账户，请留意您的银行账户信息，客服热线0571-86915761
                 */
                if (StringUtils.isNotBlank(fundCode)) {
                    fundCodeReal = "(" + fundCode + ")";
                }
                message = "【科地基金】尊敬的客户，您持有的" + fundName + fundCodeReal + "于";
                message += String.format("%02d", month) + "月" + String.format("%02d", day) + "日 " + "发放现金分红";
                message += balance + "元，资金将于2个工作日左右划入您的银行账户，请留意您的银行账户信息，客服热线0571-86915761";
                return message;
            default:
        }
        return message;
    }

    /**
     * 组合调仓发送短信：针对持仓用户发送调仓短信
     */
    @Override
    public void getPortfolioFundMessage() {
        List<FundWarehouseTransfer> fundWarehouseTransfers = fundWarehouseTransferDao.getPortfolioTransferSms();
        List<User> users = userDao.getAllUser();
        if (!fundWarehouseTransfers.isEmpty()) {
            for (FundWarehouseTransfer f : fundWarehouseTransfers) {
                for (User user : users) {
                    /**
                     *  组合份额查询
                     */
                    if (StringUtils.isBlank(user.getExternalClientId())) {
                        continue;
                    }
                    Map<String, Object> map = new HashMap<>();
                    // 查询结果
                    List<Map<String, Object>> list = new ArrayList<>();
                    CombSharesQryDto combSharesQryDto = CombSharesQryDto.builder()
                        .request_num(GlobalConstant.MAX_REQUEST_NUM)
                        .reqry_recordsum_flag("1")
                        .client_id(user.getExternalClientId())
                        .portfolio_code(f.getCombinationCode())
                        .qry_beginrownum("1")
                        .build();
                    map = hsCombSharesQryService.query(combSharesQryDto);
                    list = new ArrayList<>();
                    BaseResult result = new BaseResult();
                    HundsunUtils.ConvertToList(map, list, result);
                    if (!result.getSuccess()) {
                        log.warn("组合调仓发送短信，查询用户持仓失败。");
                        continue;
                    }
                    List<CombSharesQryModel> combSharesQryModels = ModelPopulateUtils.populateCombSharesQry(list);
                    if (combSharesQryModels != null && !combSharesQryModels.isEmpty()) {
                        CombSharesQryModel combSharesQryModel = combSharesQryModels.get(0);
                        if (combSharesQryModel.getFundShare().compareTo(BigDecimal.valueOf(0)) > 0) {
                            String message = "【科地基金】尊敬的客户，您持有的";
                            int startMonth = DateUtils.getMonth(f.getBeginDate());
                            int startDay = DateUtils.getDay(f.getBeginDate());
                            int endMonth = DateUtils.getMonth(f.getEndDate());
                            int endDay = DateUtils.getDay(f.getEndDate());

                            String sm = String.format("%02d", startMonth);
                            String sd = String.format("%02d", startDay);
                            String em = String.format("%02d", endMonth);
                            String ed = String.format("%02d", endDay);
                            message += f.getCombinationName();
                            message += "将于" + sm + "月" + sd + "日起进行调仓，您可于" + em + "月" + ed + "日" +
                                "之前登录科地基金APP选择一键跟调操作，及时跟随组合最新配置策略。仅供投资者参考，不构成投资建议。";
                            String m = smsSimpleService.sendMessage(user.getUserMobile(), message, GeneratorUtil.getRandomNum(6));
                            log.info("调仓：{}", m);
                            log.info("组合调仓发送短信：针对持仓用户发送调仓短信。短信内容：{}", message);
                        }

                    }
                }
                f.setSmsState(1);
                fundWarehouseTransferDao.updateOne(f);

            }
        }
    }
}
